<?php

namespace App\Http\Controllers\Api\Search;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Services\RecruitService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $page  = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $sortField  = $request->input('sort', 'updated_at');
        $orderRule = $request->input('order', 'desc');

        $searchWords =  $request->input('search_words', '');
        $city = $request->input('city', '');
        $recruitCateName = $request->input('recruit_cate_name', '');
        $verifyType = $request->input('verify_type');

        $where[] = ['status', 2];
        $orWhere = [];
        if (!empty($searchWords)) {
            $where[] = ['title', 'like', '%' .$searchWords. '%'];
            $orWhere[] = ['recruit_cate_name', 'like', '%' .$searchWords. '%'];
        }

        if (!empty($city)) {
            $where[] = ['city', $city];
        }

        if (!empty($recruitCateName)) {
            $where[] = ['recruit_cate_name', $recruitCateName];
        }

        if (!is_null($verifyType)) {
            $where[] = ['verify_type', $verifyType];
        }

        $recruitTableColumns = ["id", "user_id", "city", "contact_phone", "verify_type", "updated_at", "title"];
        $userTableColumns = ['id', 'avatar', 'nickname'];

        try {
            $data = (new RecruitService())->getRecruitList($page, $limit, $sortField, $orderRule, $recruitTableColumns, $userTableColumns, $where, $orWhere);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }

        return result(0, 'ok', $data);
    }

    /**
     * 获取 banner
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request): JsonResponse
    {
        /*$rule        = [
           "id" => "required|integer"
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }*/
        // 先默认写死取 id=2 的 banner 位
        $id = ['id' => 2];
        $banner = Banner::getBannerById($id);
        return result(0, 'ok', $banner);
    }

}
